<?php
/*******************************************************************************
 * $Date:: Jan 10, 2011 10:41:52 PM                                            $
 * $Revision:                                                                  $
 * $Author:: Tuan Duong                                                        $
 * $Comment::                                                                  $
 ******************************************************************************/ 
/**
 * Description here...
 * 
 * @package Lua
 * @subpackage ##Subpackage##
 * @author Tuan Duong <bacduong[at]gmail[dot]com>
 * @version 
 */

class Lua_Table_Abstract extends Zend_Db_Table_Abstract
{
    protected $autoFillTimestamps = true;

    protected $currentUserId = 1;
    static protected $initializedUtf8;
    public function __construct()
    {
        parent::__construct();
        if (!self::$initializedUtf8) {
            $this->getDefaultAdapter()->query("SET NAMES 'utf8'");
            self::$initializedUtf8 = true;
        }
        $loggedUser = Lua_Util_Session::getLoggedUser();
        if (!$loggedUser->isEmpty()) {
            $this->currentUserId = (int) $loggedUser->id;
        }
        $this->autoFillTimestamps = true;
    }

    /**
     * @param array $data
     * @return int The primary key of row inserted
     */
    public function insert(array $data)
    {
        if ($this->autoFillTimestamps && !isset($data['created_time'])) {
            $data['created_time'] = date('Y-m-d H:i:s');
        }
        return parent::insert($data);
    }

    public function update($data, $where)
    {
    	/**
    	 * FIXME: this causes error if table does not have modified_user_id column. Ex: ipoo_user
    	 */
    	/*
        if (!isset($data['modified_user_id'])) {
            $data['modified_user_id'] = $this->currentUserId;
        }
        */
        return parent::update($data, $where);
    }

    /**
     * Get table name
     * @return string
     */
    protected function getTableName()
    {
        return $this->_name;
    }

    /**
     * Set table name
     * @param string $tableName
     */
    public function setTableName($tableName)
    {
        $this->_name = $tableName;
    }

    /**
     * Build bean from datarow
     * @param array|Zend_Db_Table_Row_Abstract $rowData
     * @return Lua_Bean_Abstract
     */
    protected function buildBean($rowData)
    {
        $class = "Lua_Bean_" . Lua_Util_Common::toCamelCase($this->_name);
    	$model = new $class();
    	/* @var $model Lua_Bean_Abstract */
    	$model->bindData($rowData);
    	return $model;
    }
    
    public function findByProperties(array $properties) {
        $select = $this->select($properties);
        $rows = $this->fetchAll($select);
        return $rows;
    }
}